package cron

import (
	"time"

	"github.com/astaxie/beego"
	"publish/app/account/model"
	"publish/pub-lib"
	"runtime/debug"
)


type TimeoutWorker struct {
	ticker         *time.Ticker
	tick           int64
}

func (w *TimeoutWorker) run() {
	defer func() {
		if r := recover(); r != nil {
			debug.PrintStack()
			beego.Error("[recover]", r)
		}
	}()

	w.ticker = time.NewTicker(time.Second * time.Duration(w.tick))

	for {
		select {
		case <-w.ticker.C:
			accounts, err := model.ListAccount()
			if err != nil {
				continue
			}

			for i := range accounts {
				CheckAccount(accounts[i])
			}
		}
	}
}

func CheckAccount(account model.Account){
	params := map[string]string{
		"appid":account.PlatParams,
	}
	platform := pub_lib.NewPlatform(account.Plat,account.Cookie,params)
	if err := platform.CheckCookie();err != nil{
		beego.Error(err.Error())
		account.Status = 2
		model.UpdateAccount(account)
		return
	}

	account.Status = 1
	model.UpdateAccount(account)
	beego.Info("平台:",account.Plat,"账号:",account.Username,"检查通过")
}


func StartWorker() {
	tick := beego.AppConfig.DefaultInt64("timer_tick", 60)

	work := &TimeoutWorker{
		tick:           tick,
	}

	go work.run()
}


